package com.example.guiguiapplicatio.fragment.FamilySigning.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.guiguiapplicatio.api.Interface.Api;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.FamilyarChivesRecordList;
import com.example.guiguiapplicatio.Response.FamilyarChooseService;
import com.example.guiguiapplicatio.Response.ServicePackageResponse;
import com.example.guiguiapplicatio.fragment.home.adapter.ServicepacksListAdapter;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FamilySigningAdapter extends RecyclerView.Adapter<FamilySigningAdapter.FamilySigningViewHolder> {
    private Context mContext;
    private Api api;
    private List<ServicePackageResponse> packageResponseList = new ArrayList<>();
    private ServicepacksListAdapter ServicepacksListadapter;
    private List<FamilyarChooseService> familyarChooseServiceList = new ArrayList<>();
    private OnServicePackageSelectedListener2 listener2;

    private List<FamilyarChivesRecordList> familyarChivesRecordLists;

    public FamilySigningAdapter(List<FamilyarChivesRecordList> familyarChivesRecordLists, Context context, Api api , OnServicePackageSelectedListener2 listener2) {
        this.familyarChivesRecordLists = familyarChivesRecordLists;
        mContext = context;
        this.api = api;
        this.listener2 = listener2;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public FamilySigningViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_total_detail_family_sign_item, parent, false);
        return new FamilySigningViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull FamilySigningViewHolder holder, int position) {
        FamilyarChivesRecordList familyarChivesRecordList = familyarChivesRecordLists.get(position);
        holder.examination_name.setText(familyarChivesRecordList.getName());
        holder.examination_sex.setText(familyarChivesRecordList.getSex());
        holder.examination_age.setText(familyarChivesRecordList.getAge().toString() + "岁");
        holder.examination_id.setText(familyarChivesRecordList.getIdcard());
        holder.examination_people_type.setText(familyarChivesRecordList.getListenername().toString());
        holder.confirm_the_contract2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] items = {"基础服务包", "地方新增服务包"};
                AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
                dialog.setTitle("选择服务包类型")
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                showServicePackageSelectionDialog(holder, familyarChivesRecordList.getIdcard(), items[which].toString());
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                dialog.show();
            }
        });
//        GridLayoutManager layoutManager = new GridLayoutManager(mContext, 2);
        FlexboxLayoutManager layoutManager =new FlexboxLayoutManager(mContext);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        holder.examination_start_list.setLayoutManager(layoutManager);
    }

    @Override
    public int getItemCount() {
        return familyarChivesRecordLists.size();
    }

    public static class FamilySigningViewHolder extends RecyclerView.ViewHolder {
        TextView examination_name;
        TextView examination_sex;
        TextView examination_age;
        TextView examination_id;
        TextView examination_people_type;
        Button confirm_the_contract2;
        RecyclerView examination_start_list;

        public FamilySigningViewHolder(@NonNull View itemView) {
            super(itemView);
            examination_name = itemView.findViewById(R.id.examination_name);
            examination_sex = itemView.findViewById(R.id.examination_sex);
            examination_age = itemView.findViewById(R.id.examination_age);
            examination_id = itemView.findViewById(R.id.examination_id);
            examination_people_type = itemView.findViewById(R.id.examination_people_type);
            examination_start_list = itemView.findViewById(R.id.examination_start_list);
            confirm_the_contract2 = itemView.findViewById(R.id.confirm_the_contract2);
//            examination_people_type = itemView.findViewById(R.id.examination_people_type);
        }
    }

    private void showServicePackageSelectionDialog(FamilySigningViewHolder viewHolder, String Idcard, String type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("选择服务包");

        View dialogView = View.inflate(mContext, R.layout.dialog_service_package, null);
        RecyclerView recyclerView = dialogView.findViewById(R.id.service_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        Call<ResponseBody<List<ServicePackageResponse>>> call = api.getServicePackByType(type);
        call.clone().enqueue(new Callback<ResponseBody<List<ServicePackageResponse>>>() {
            @Override
            public void onResponse(Call<ResponseBody<List<ServicePackageResponse>>> call, Response<ResponseBody<List<ServicePackageResponse>>> response) {
                ResponseBody<List<ServicePackageResponse>> responseBody = response.body();
                if (responseBody != null && responseBody.getData() != null) {
                    ServicepacksListadapter = new ServicepacksListAdapter(responseBody.getData());
                    recyclerView.setAdapter(ServicepacksListadapter);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody<List<ServicePackageResponse>>> call, Throwable t) {

            }
        });
        builder.setView(dialogView);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                packageResponseList = ServicepacksListadapter.getSelectedItems();
                if(familyarChooseServiceList.size() == 0){
                    FamilyarChooseService F = new FamilyarChooseService(Idcard,packageResponseList);
                    familyarChooseServiceList.add(F);
                }
                boolean isExisting = false;
                for (FamilyarChooseService existingService : familyarChooseServiceList) {
                    if (existingService.getIdcard().equals(Idcard)) {
                        // 如果已存在相同Idcard的对象，则更新该对象的服务包列表
                        List<ServicePackageResponse> existingServicePackageList = existingService.getServicePackageResponseList();
                        for (ServicePackageResponse packageResponse : packageResponseList) {
                            String newId = packageResponse.getId();
                            boolean isPackageExisting = false;
                            for (ServicePackageResponse existingPackage : existingServicePackageList) {
                                String existingId = existingPackage.getId();
                                if (existingId.equals(newId)) {
                                    isPackageExisting = true;
                                    break;
                                }
                            }
                            if (!isPackageExisting) {
                                existingServicePackageList.add(packageResponse);
                            }
                        }
                        isExisting = true;
                        break;
                    }
                }

                // 如果不存在相同Idcard的对象，则创建一个新的FamilyarChooseService对象，并添加到列表中
                if (!isExisting) {
                    FamilyarChooseService newFamilyarChooseService = new FamilyarChooseService(Idcard, packageResponseList);
                    familyarChooseServiceList.add(newFamilyarChooseService);
                }
                FamilyarChooseService familyarchooseService = new FamilyarChooseService();
                for (FamilyarChooseService familyarChooseService : familyarChooseServiceList){
                    if(familyarChooseService.getIdcard().equals(Idcard)){
                        familyarchooseService = familyarChooseService;
                        break;
                    }
                    else {
                        familyarchooseService = new FamilyarChooseService(Idcard,packageResponseList);
                    }
                }
                viewHolder.examination_start_list.setAdapter(new FamilySigningServiceAdapter(familyarchooseService, new OnServicePackageSelectedListener() {
                    @Override
                    public void onServicePackagesSelected(FamilyarChooseService familyarchooseService) {
                        listener2.onServicePackagesSelected(familyarChooseServiceList);
                    }
                }));
                listener2.onServicePackagesSelected(familyarChooseServiceList);
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

}
